package com.soft.controller;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.soft.entity.User;
import com.soft.service.UserService;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 用户接口（/user）：
 * - 账号基础：登录、注册、校验、信息查询与更新（历史接口多为字符串返回，沿用）
 * - 管理端：分页列表、单查、增删改（需请求头 X-User-Id 对应 admin 角色）
 * - 自助：/self 获取与更新自身信息、修改密码
 */
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /** 登录（简化版）：明文或已加密兼容，返回提示字符串 */
    @RequestMapping("/login")
    public String login(String username, String password) {
    // 1) 调用服务层校验账号密码（兼容明文/加密）
    User user = userService.login(username, password);
    // 2) 返回固定提示字符串（沿用历史前端约定）
        if (user != null) {
            return "登录成功";
        }
        return "用户名或密码错误";
    }

    /** 注册：校验用户名/邮箱唯一性，成功返回“注册成功” */
    @RequestMapping("/register")
    public String register(String username, String password, String email,String phone) {
    // 1) 校验用户名是否存在
        if (userService.checkUsernameExist(username)) {
            return "用户名已存在";
        }
        
    // 2) 校验邮箱是否被占用
        if (userService.checkEmailExist(email)) {
            return "邮箱已被使用";
        }
        
    // 3) 执行注册
    User registeredUser = userService.register(username, password, email,phone);
    // 4) 按结果返回提示
        if (registeredUser != null) {
            return "注册成功";
        }
        return "注册失败";
    }

    @RequestMapping("/check/username")
    public String checkUsername(String username) {
        boolean exists = userService.checkUsernameExist(username);
        return exists ? "用户名已存在" : "用户名可用";
    }
    
    @RequestMapping("/getUserId")
    public Integer getUserId(String username) {
        Integer userId = userService.getUserIdByUsername(username);
        return userId != null ? userId : 0;
    }

    @RequestMapping("/getUserIdByEmail")
    public String getUserIdByEmail(String email) {
        Integer userId = userService.getUserIdByEmail(email);
        return userId != null ? userId.toString() : "用户不存在";
    }

    @RequestMapping("/check/email")
    public String checkEmail(String email) {
        boolean exists = userService.checkEmailExist(email);
        return exists ? "邮箱已被使用" : "邮箱可用";
    }

    @RequestMapping("/get/nickname")
    public String getNickname(String username) {
        String nickname = userService.getNicknameByUsername(username);
        return nickname != null ? nickname : "用户不存在";
    }

    @GetMapping("/get/nicknameById")
    public String getNicknameById(@RequestParam Integer userId) {
        String nickname = userService.getNicknameByUserId(userId);
        return nickname != null ? nickname : "用户不存在";
    }

    @RequestMapping("/get/email")
    public String getEmail(String username) {
        String email = userService.getEmailByUsername(username);
        return email != null ? email : "用户不存在";
    }

    @RequestMapping("/get/phone")
    public String getPhone(String username) {
        String phone = userService.getPhoneByUsername(username);
        return phone != null ? phone : "用户不存在";
    }

    @RequestMapping("/get/role")
    public String getRole(String username) {
        String role = userService.getRoleByUsername(username);
        return role != null ? role : "用户不存在";
    }

    @RequestMapping("/get/status")
    public String getStatus(String username) {
        String status = userService.getStatusByUsername(username);
        return status != null ? status : "用户不存在";
    }

    @RequestMapping("/get/createTime")
    public String getCreateTime(String username) {
        LocalDateTime createTime = userService.getCreateTimeByUsername(username);
        return createTime != null ? createTime.toString() : "用户不存在";
    }

    @RequestMapping("/update/nickname")
    public String updateNickname(String username, String newNickname) {
        if (userService.updateNickname(username, newNickname)) {
            return "昵称更新成功";
        }
        return "更新失败，用户不存在";
    }

    @RequestMapping("/update/email")
    public String updateEmail(String username, String newEmail) {
        if (userService.updateEmail(username, newEmail)) {
            return "邮箱更新成功";
        }
        return "更新失败，用户不存在或邮箱已被使用";
    }

    @RequestMapping("/update/phone")
    public String updatePhone(String username, String newPhone) {
        if (userService.updatePhone(username, newPhone)) {
            return "电话更新成功";
        }
        return "更新失败，用户不存在";
    }

    @RequestMapping("/update/role")
    public String updateRole(String username, String newRole) {
        if (userService.updateRole(username, newRole)) {
            return "角色更新成功";
        }
        return "更新失败，用户不存在";
    }

    @RequestMapping("/update/status")
    public String updateStatus(String username, String newStatus) {
        if (userService.updateStatus(username, newStatus)) {
            return "状态更新成功";
        }
        return "更新失败，用户不存在";
    }

    @RequestMapping("/update/password")
    public String updatePassword(String username, String oldPassword, String newPassword) {
        int result = userService.updatePassword(username, oldPassword, newPassword);
        return switch (result) {
            case 1 -> "密码修改成功";
            case 0 -> "旧密码错误";
            case -1 -> "用户不存在";
            default -> "修改失败";
        };
    }

    // ================= 管理端：用户管理 =================
    private boolean isAdmin(HttpServletRequest req) {
    // 解析头 X-User-Id，判定是否为 admin 角色
    if (req == null) return false;
        String h = req.getHeader("X-User-Id");
        if (h == null || h.isEmpty()) return false;
        try {
            Integer uid = Integer.valueOf(h);
            User u = userService.getById(uid);
            return u != null && "admin".equalsIgnoreCase(u.getRole());
        } catch (NumberFormatException ex) {
            return false;
        }
    }

    private Integer currentUserId(HttpServletRequest req) {
        if (req == null) return null;
        String h = req.getHeader("X-User-Id");
        if (h == null || h.isEmpty()) return null;
        try { return Integer.valueOf(h); } catch (NumberFormatException ex) { return null; }
    }

    /**
     * 管理端：分页查询用户
     * 需要：X-User-Id 对应 admin
     * 返回：{ records, total, page, size }
     */
    @GetMapping("/list")
    public ResponseEntity<?> list(@RequestParam(required = false) String keyword,
                                  @RequestParam(required = false, defaultValue = "1") Integer page,
                                  @RequestParam(required = false, defaultValue = "10") Integer size,
                                  HttpServletRequest req) {
    // 1) 鉴权：仅 admin 可访问
    if (!isAdmin(req)) return ResponseEntity.status(403).body("forbidden");
    // 2) 归一化分页参数（页码最小为1，size限制最大200）
    int p = page == null ? 1 : Math.max(1, page);
    int s = size == null ? 10 : Math.max(1, Math.min(size, 200));
    // 3) 查询统计
    long total = userService.countUsers(keyword);
    List<User> records = userService.listUsersPage(keyword, p, s);
    // 4) 组装响应
    Map<String, Object> resp = new HashMap<>();
    resp.put("records", records);
    resp.put("total", total);
    resp.put("page", p);
    resp.put("size", s);
    return ResponseEntity.ok(resp);
    }

    /** 管理端：按 ID 获取用户 */
    @GetMapping("/{id}")
    public ResponseEntity<?> get(@PathVariable Integer id, HttpServletRequest req) {
        if (!isAdmin(req)) return ResponseEntity.status(403).body("forbidden");
        User u = userService.getById(id);
        if (u == null) return ResponseEntity.notFound().build();
        return ResponseEntity.ok(u);
    }

    // ========= 自助：获取/更新自身信息 =========
    /** 自助：获取自身信息（从 X-User-Id 识别） */
    @GetMapping("/self")
    public ResponseEntity<?> getSelf(HttpServletRequest req) {
    // 1) 从请求头识别当前用户
    Integer uid = currentUserId(req);
        if (uid == null) return ResponseEntity.status(401).body("unauthorized");
    // 2) 查询并返回
    User u = userService.getById(uid);
        if (u == null) return ResponseEntity.status(401).body("unauthorized");
        return ResponseEntity.ok(u);
    }

    /** 自助：更新自身信息（仅覆盖 body 传入字段） */
    @PutMapping("/self")
    public ResponseEntity<?> updateSelf(@RequestBody User body, HttpServletRequest req) {
    // 1) 身份识别
    Integer uid = currentUserId(req);
        if (uid == null) return ResponseEntity.status(401).body("unauthorized");
    // 2) 仅覆盖 body 中提供的字段
    body.setUserId(uid);
    boolean ok = userService.updateUserById(body);
        if (!ok) return ResponseEntity.badRequest().body("更新失败");
        return ResponseEntity.ok("OK");
    }

    public static class UserCreateReq {
        public String username;
        public String password;
        public String email;
        public String phone;
        public String role; // admin/member
        public String status; // active/inactive
    }

    /** 管理端：创建用户 */
    @PostMapping
    public ResponseEntity<?> create(@RequestBody UserCreateReq body, HttpServletRequest req) {
        if (!isAdmin(req)) return ResponseEntity.status(403).body("forbidden");
        User u = userService.createUser(body.username, body.password, body.email, body.phone, body.role, body.status);
        if (u == null) return ResponseEntity.badRequest().body("创建失败");
        Map<String, Object> resp = new HashMap<>();
        resp.put("id", u.getUserId());
        return ResponseEntity.ok(resp);
    }

    /** 管理端：更新用户 */
    @PutMapping("/{id}")
    public ResponseEntity<?> update(@PathVariable Integer id, @RequestBody User body, HttpServletRequest req) {
        if (!isAdmin(req)) return ResponseEntity.status(403).body("forbidden");
        body.setUserId(id);
        boolean ok = userService.updateUserById(body);
        if (!ok) return ResponseEntity.badRequest().body("更新失败");
        return ResponseEntity.ok("OK");
    }

    /** 管理端：删除用户 */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> delete(@PathVariable Integer id, HttpServletRequest req) {
        if (!isAdmin(req)) return ResponseEntity.status(403).body("forbidden");
        boolean ok = userService.deleteUserById(id);
        if (!ok) return ResponseEntity.badRequest().body("删除失败");
        return ResponseEntity.ok("OK");
    }

    public static class PasswordUpdateReq {
        public String oldPassword;
        public String newPassword;
    }

    // 给前端自助修改密码（需要前端提供用户名或采用登录态，这里沿用原简化设计：从 body.oldPassword 校验）
    /**
     * 管理端/自助：按 ID 修改密码
     * - 管理员：可直接重置
     * - 普通用户：需校验旧密码
     */
    @PutMapping("/{id}/password")
    public ResponseEntity<?> updatePasswordById(@PathVariable Integer id, @RequestBody PasswordUpdateReq body, HttpServletRequest req) {
        // 允许本人或管理员修改；当前无会话体系，简化：管理员放行，普通用户需旧密码校验
        User u = userService.getById(id);
        if (u == null) return ResponseEntity.notFound().build();
        if (isAdmin(req)) {
            // 管理员直接重置密码
            boolean ok = userService.updateUserById(new User() {{ setUserId(id); setPassword(body.newPassword); }});
            return ok ? ResponseEntity.ok("OK") : ResponseEntity.badRequest().body("更新失败");
        }
        int code = userService.updatePassword(u.getUsername(), body.oldPassword, body.newPassword);
        if (code == 1) return ResponseEntity.ok("OK");
        if (code == 0) return ResponseEntity.status(400).body("旧密码错误");
        if (code == -1) return ResponseEntity.status(404).body("用户不存在");
        return ResponseEntity.badRequest().body("更新失败");
    }

    /** 自助：修改自身密码 */
    @PutMapping("/self/password")
    public ResponseEntity<?> updatePasswordSelf(@RequestBody PasswordUpdateReq body, HttpServletRequest req) {
        Integer uid = currentUserId(req);
        if (uid == null) return ResponseEntity.status(401).body("unauthorized");
        User u = userService.getById(uid);
        if (u == null) return ResponseEntity.status(401).body("unauthorized");
        int code = userService.updatePassword(u.getUsername(), body.oldPassword, body.newPassword);
        if (code == 1) return ResponseEntity.ok("OK");
        if (code == 0) return ResponseEntity.status(400).body("旧密码错误");
        if (code == -1) return ResponseEntity.status(404).body("用户不存在");
        return ResponseEntity.badRequest().body("更新失败");
    }
}
